package JackSu.aobing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class ThreadExceptionTest implements Runnable {

    static Logger logger = LoggerFactory.getLogger(ThreadExceptionTest.class);

    @Override
    public void run() {
        Thread thread = Thread.currentThread();
        System.out.println("eh =" + thread.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }

    static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("线程异常：" + e);
            logger.error("ThreadPool {} got exception", t,e);
        }
    }

    static class HandlerThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
            return thread;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        try{
////            异常无法捕获
//            ExecutorService executorService = Executors.newCachedThreadPool();
//            executorService.execute(new ThreadExceptionTest());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        ExecutorService executorService = Executors.newCachedThreadPool(new HandlerThreadFactory());
        Future<String> submit = executorService.submit(new ThreadExceptionTest(), "执行成功");
        executorService.shutdown();
        Object o = submit.get();
        System.out.println(o);
    }
}
